package org.jeecg.common.util;


import org.apache.http.ParseException;
import org.apache.http.client.methods.CloseableHttpResponse;
import org.apache.http.client.methods.HttpGet;
import org.apache.http.client.utils.URIBuilder;
import org.apache.http.impl.client.CloseableHttpClient;
import org.apache.http.impl.client.HttpClients;
import org.apache.http.util.EntityUtils;

import javax.servlet.http.HttpServletRequest;
import java.io.IOException;
import java.net.URI;
import java.net.URISyntaxException;
import java.util.regex.Matcher;
import java.util.regex.Pattern;

/**
 * IP工具类
 */
public class IPUtil {

    public static final String SEMICOLON = ";";

    // Nginx代理传递的实际客户端 IP-header
    public static final String[] HEADERS_TO_TRY = {
            "X-Forwarded-For",
            "X-REAL-IP",
            "Proxy-Client-IP",
            "WL-Proxy-Client-IP",
            "HTTP_X_FORWARDED_FOR",
            "HTTP_X_FORWARDED",
            "HTTP_X_CLUSTER_CLIENT_IP",
            "HTTP_CLIENT_IP",
            "HTTP_FORWARDED_FOR",
            "HTTP_FORWARDED",
            "HTTP_VIA",
            "REMOTE_ADDR",
            "REMOTE-HOST"
    };


    /**
     * 获取客户端的IP地址
     */
    public static String getClientIp(HttpServletRequest request) {
        String clientIp = _getClientIp(request);
        if (null != clientIp && !clientIp.trim().isEmpty()) {
            return clientIp;
        }
        return request.getRemoteAddr();
    }


    private static String _getClientIp(HttpServletRequest request) {
        for (String header : HEADERS_TO_TRY) {
            String ip = request.getHeader(header);
            if (ip != null && ip.length() != 0 && !"unknown".equalsIgnoreCase(ip)) {
                return ip;
            }
        }
        return request.getRemoteAddr();
    }

    //    https://ip.ws.126.net/ipquery?ip=54.10.32.120
    public static IPInfo _getIPInfoFrom126(String ip) {
        CloseableHttpClient httpclient = HttpClients.createDefault();
        URI uri = null;
        try {
            uri = new URIBuilder("https://ip.ws.126.net/ipquery").setParameter("id", ip).build();
        } catch (URISyntaxException e) {
            return null;
        }
        HttpGet httpGet = new HttpGet(uri);
        CloseableHttpResponse response = null;
        try {
            try {
                response = httpclient.execute(httpGet);
            } catch (IOException e) {
                return null;
            }
            if (response.getStatusLine().getStatusCode() == 200) {
                String content = null;
                try {
                    content = EntityUtils.toString(response.getEntity(), "UTF-8");
                } catch (ParseException | IOException e) {
                    return null;
                }
                String patternString = "\\{city:\"(?<cityName>.*?)\", province:\"(?<provinceName>.*?)\"}";
                Pattern pattern = Pattern.compile(patternString);
                Matcher matcher = pattern.matcher(content);

                if (matcher.find()) {
                    IPInfo info = new IPInfo();
                    String provinceName = matcher.group("provinceName");
                    String cityName = matcher.group("cityName");
                    if (oConvertUtils.isNotEmpty(provinceName)) info.setProvinceName(provinceName);
                    if (oConvertUtils.isNotEmpty(cityName)) info.setCityName(cityName);

                    return info;
                }

                return null;
            }
        } finally {
            if (response != null) {
                try {
                    response.close();
                } catch (IOException ignored) {
                }
            }

            try {
                httpclient.close();
            } catch (IOException ignored) {
            }
        }
        return null;
    }

    public static IPInfo _getIPInfoFromBaidu(String ip) {

        return null;
    }

    public static IPInfo _getIPInfoFromIqiyi(String ip) {

        return null;
    }

    public static IPInfo getIPInfo(String ip) throws URISyntaxException, IOException {
        return _getIPInfoFrom126(ip);
    }


//   网易云
//    http://ip.ws.126.net/ipquery?ip=54.10.32.120
//    http://opendata.baidu.com/api.php?query=117.136.12.79&co=&resource_id=6006&oe=utf8
//    爱奇艺
//    http://ip.geo.iqiyi.com/cityjson?format=json&ip=[IP地址]
//    太平洋
//    http://whois.pconline.com.cn/ipJson.jsp?ip=[IP地址]&json=true
//    腾讯接口
//    https://apis.map.qq.com/ws/location/v1/ip?output=json&key=KUQBZ-FYDCU-YMVVN-2DDW5-7WDYE-5JBJR&ip=[IP地址]
//    http://www.ipip.net/
//    http://ip.taobao.com/service/getIpInfo.php?ip=
//    https://lenjor.github.io/2020/12/IP-Adress-Location-Util/
}
